package com.example.xxljobaiassistant.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.xxljobaiassistant.service.XxlJobService;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("XxlJobTools")
public class XxlJobTools {

    @Autowired
    private XxlJobService xxlJobService;

    @Tool(name = "获取执行器列表", value = "获取所有可用的XXL-JOB执行器，显示执行器ID、名称和地址信息")
    public String getExecutors() {


        String result = xxlJobService.listExecutors();

        try {
            JSONObject json = JSON.parseObject(result);
            if (json == null) {
                return "获取执行器列表失败: 响应为空";
            }

            JSONArray dataArr = json.getJSONArray("data");
            if (dataArr == null) {
                return "获取执行器列表失败: data对象为空";
            }

            StringBuilder sb = new StringBuilder(128 + dataArr.size() * 64); // 预分配合理容量
            sb.append("找到").append(dataArr.size()).append("个执行器:\n\n");

            for (int i = 0; i < dataArr.size(); i++) {
                JSONObject executor = dataArr.getJSONObject(i);
                Integer id = executor.getInteger("id");
                String name = executor.getString("appname");
                String address = executor.getString("addressList");

                sb.append("ID: ").append(id)
                        .append(", 名称: ").append(name)
                        .append(", 地址: ").append(address)
                        .append("\n");
            }

            return sb.toString();

        } catch (Exception e) {
            // 建议加入日志：log.error("解析执行器列表失败", e);
            return "获取执行器列表失败: 数据解析异常";
        }
    }


    @Tool(name = "获取任务列表", value = "获取所有配置的任务，显示任务ID、名称、所属执行器和调度规则")
    public String getJobs() {
        String result = xxlJobService.listJobs();
        JSONObject json = JSON.parseObject(result);

        try {
            // 直接从根对象获取data数组，而不是从data.data
            JSONArray data = json.getJSONArray("data");
            int recordsTotal = json.getIntValue("recordsTotal");

            if (data == null || data.isEmpty()) {
                return "没有找到任何任务";
            }

            StringBuilder sb = new StringBuilder();
            sb.append("找到").append(recordsTotal).append("个任务:\n\n");

            for (int i = 0; i < data.size(); i++) {
                JSONObject job = data.getJSONObject(i);
                sb.append("ID: ").append(job.getInteger("id"))
                        .append(", 任务名: ").append(job.getString("jobDesc"))
                        .append(", 执行器: ").append(job.getInteger("jobGroup"));

                // 添加调度规则
                String scheduleType = job.getString("scheduleType");
                String scheduleConf = job.getString("scheduleConf");
                sb.append(", 调度规则: ").append(scheduleType);
                if (scheduleConf != null && !scheduleConf.isEmpty()) {
                    sb.append("(").append(scheduleConf).append(")");
                }

                // 添加执行器处理器
                String executorHandler = job.getString("executorHandler");
                if (executorHandler != null && !executorHandler.isEmpty()) {
                    sb.append(", 处理器: ").append(executorHandler);
                }

                // 添加任务状态
                int triggerStatus = job.getIntValue("triggerStatus");
                sb.append(", 状态: ").append(triggerStatus == 1 ? "运行中" : "已停止");

                sb.append("\n");
            }
            return sb.toString();
        } catch (Exception e) {
            // 添加异常信息，便于调试
            return "解析任务列表数据失败: " + e.getMessage() + "\n原始数据: " + result;
        }
    }


    @Tool(name = "执行任务", value = "根据任务ID触发一个任务立即执行，可以提供可选的执行参数")
    public String triggerJob(
            @dev.langchain4j.agent.tool.P("任务的ID") int jobId,
            @dev.langchain4j.agent.tool.P("可选的执行参数，JSON格式") String executorParam) {
        String result = xxlJobService.triggerJob(jobId, executorParam);
        JSONObject json = JSON.parseObject(result);

        if (json.getInteger("code") == 200) {
            return "任务已成功触发，任务ID: " + jobId;
        } else {
            return "触发任务失败: " + json.getString("msg");
        }
    }

    // XxlJobTools
    @Tool(name = "查询任务日志", value = "根据任务ID和时间范围查询任务的执行日志列表，显示日志ID、触发时间和执行状态")
    public String queryJobLogList(
            @dev.langchain4j.agent.tool.P("任务的ID") int jobId,
            @dev.langchain4j.agent.tool.P("可选的时间范围，例如：2023-06-01 00:00:00 - 2023-06-02 00:00:00") String filterTime) {

        String result = xxlJobService.queryJobLogs(jobId, filterTime, 0, 10);
        JSONObject json = JSON.parseObject(result);

        try {
            // 直接获取data数组
            JSONArray data = json.getJSONArray("data");
            int recordsTotal = json.getIntValue("recordsTotal");

            if (data == null || data.isEmpty()) {
                return "未找到任务ID为" + jobId + "的日志记录";
            }

            StringBuilder sb = new StringBuilder();
            sb.append("找到").append(recordsTotal).append("条日志记录:\n\n");

            for (int i = 0; i < data.size(); i++) {
                JSONObject log = data.getJSONObject(i);

                // 获取状态
                int triggerCode = log.getIntValue("triggerCode");
                int handleCode = log.getIntValue("handleCode");
                String status;

                if (triggerCode == 200) {
                    if (handleCode == 200) {
                        status = "执行成功";
                    } else if (handleCode == 0) {
                        status = "执行中";
                    } else {
                        status = "执行失败";
                    }
                } else {
                    status = "触发失败";
                }

                // 基本信息
                sb.append("日志ID: ").append(log.getInteger("id"))
                        .append("\n任务ID: ").append(log.getInteger("jobId"))
                        .append("\n执行器ID: ").append(log.getInteger("jobGroup"))
                        .append("\n执行器处理器: ").append(log.getString("executorHandler"))
                        .append("\n触发时间: ").append(log.getString("triggerTime"))
                        .append("\n状态: ").append(status)
                        .append("\n");

                // 添加触发信息
                String triggerMsg = log.getString("triggerMsg");
                if (triggerMsg != null && !triggerMsg.isEmpty()) {
                    // 移除HTML标签，提取纯文本
                    triggerMsg = triggerMsg.replaceAll("<[^>]*>", " ");
                    // 去除多余空格
                    triggerMsg = triggerMsg.replaceAll("\\s+", " ").trim();
                    sb.append("\n触发信息: ").append(triggerMsg).append("\n");
                }

                // 添加处理信息
                String handleMsg = log.getString("handleMsg");
                if (handleMsg != null && !handleMsg.isEmpty()) {
                    sb.append("\n处理信息: ").append(handleMsg).append("\n");
                }

                // 添加执行参数(如果需要)
                String executorParam = log.getString("executorParam");
                if (executorParam != null && !executorParam.isEmpty()) {
                    sb.append("\n执行参数: ").append(executorParam).append("\n");
                }

                sb.append("\n--------------------\n");
            }
            return sb.toString();
        } catch (Exception e) {
            return "解析任务日志数据失败: " + e.getMessage() + "\n原始数据: " + result;
        }
    }





}